<?php

defined('BASEPATH') or exit('No direct script access allowed');

/**
 * Description of Shopping
 *
 * @author doufu <442958506@qq.com>
 */
class Shopping extends REST_Member_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->library('form_validation');
	}

	/**
	 * 下单接口
	 */
	public function book() {
		if ($this->isGuest()) {
			$this->renderJson(10002);
		}
		$this->form_validation->validateData(array(
			'address_id',
				), array(
			array(
				'address_id',
				'required|integer'
			),
		));

		if ($this->form_validation->hasErrors()) {
			$data ['msg'] = $this->form_validation->error;
			$this->renderJson(10005, $data);
		}

		$this->load->model('api/Agent_model', 'Agent');
		$row = $this->Agent->assignment_status($this->form_validation->address_id);
		if(!$row) {
			$this->renderJson(10005);
		}
		if($row['status'] === REST_Controller::STATUS_DELETE) {
			$this->renderJson(10053);
		}
		$order = $this->post('order');
		if (empty($order)) {
			$this->renderJson(10005);
		}
		// id为小仓库商品ID
		$this->load->model('api/Product_model', 'Product');

		try {
			$this->db->trans_begin();
			$data = $this->Product->getProduct($this->form_validation->address_id);
			$tmp = $tmp1 = array();
			foreach ($data as $v) {
				$tmp[$v['id']] = $v;
				$tmp1[$v['id']] = array('stock' => $v['stock'], 'limit_num' => $v['limit_num']);
			}
			mt_srand((double) microtime() * 1000000);
			$order_no = '1' . str_pad($this->form_validation->address_id, 4, '0', STR_PAD_LEFT) . date('ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
			$orderCreate = array(
				'total_price' => 0,
				'request_num' => 0,
				'user_id' => $this->identity['uid'],
				'address_id' => $this->form_validation->address_id,
				'contact_address' => $row['contact_address'],
				'status' => '1', //未支付
				'order_num' => $order_no,
			);
			foreach ($order as &$v) {
				$id = $v['id'] = intval(isset($v['id']) ? $v['id'] : '');
				//商品是否存在
				if (intval($v['id']) < 1 || !isset($tmp[$id])) {
					$this->renderJson(10050, array('id' => $id));
				}

				//库存是否充足
				$request_num = $v['request_num'] = intval($v['request_num']);
				if ($request_num < 1 || $tmp1[$id]['stock'] < $request_num) {
					$this->renderJson(10051, array('msg' => sprintf($this->lang->line('e10051'), $tmp[$id]['productName'], $tmp[$id]['stock'])));
				} else {
					$tmp1[$id]['stock'] -= $request_num;
				}
				//是否限购产品
				if ($tmp[$id]['isLimit']) {
					if ($tmp[$id]['limit_num'] < $request_num) {
						$this->renderJson(10052, array('msg' => sprintf($this->lang->line('e10052'), $tmp[$id]['productName'], $tmp1[$id]['limit_num'])));
					} else {
						$tmp[$id]['limit_num'] -= $request_num;
					}
				}
				// 填充订单信息
				$orderCreate['total_price'] += $tmp[$id]['price'] * $request_num * 100;
				$orderCreate['request_num'] += $request_num;
				// 填充订单详情信息
				$v['sw_product_id'] = $id;
				$v['product_id'] = $tmp[$id]['product_id'];
				$v['name'] = $tmp[$id]['productName'];
				$v['price'] = $tmp[$id]['price'] * 100;
				$v['number'] = $request_num;
				$v['options'] = serialize(isset($v['options']) ? $v['options'] : '');
			}
			//减除商品库存
			$this->Product->reduce($order);
			$this->load->model('api/Order_model', 'Order');
			//获取补贴
			$subsidy = $this->Order->subsidy($orderCreate['total_price']);
			$orderCreate['subsidy'] = $subsidy;
			//获取优惠卷 省略
			//计算总运费
			$orderCreate['shipping_fee'] = 0 * 100; //数据库中运费单位为分
			$orderCreate['total_price'] += $orderCreate['shipping_fee'];
			$orderCreate['netpay'] = $orderCreate['total_price'] - $orderCreate['subsidy'];
			//创建订单
			$order_id = $this->Order->create($orderCreate, $order);
			$short_desc = sprintf($this->lang->line("s1000{$orderCreate['status']}"), $orderCreate['order_num']);
			$this->Order->log($order_id, $orderCreate['status'], $short_desc, 1);
			$tmp_1 = array(
				'data' => array(
					'order_id' => $order_id,
					'total_price' => $orderCreate['total_price'] / 100,
					'shipping_fee' => $orderCreate['shipping_fee'] / 100,
					'subsidy' => $orderCreate['subsidy'] / 100,
					'netpay' => $orderCreate['netpay'] / 100
				)
			);
			if ($this->db->trans_status() === FALSE) {
				throw new Exception();
			} else {
				$this->db->trans_commit();
			}
			$this->renderJson(11100, $tmp_1);
		} catch (Exception $e) {
			$this->db->trans_rollback();
			$this->renderJson(11200);
		}
	}

	/**
	 * 支付接口
	 */
	public function pay() {
		$this->form_validation->validateData(array(
			'orderId', 'orderAddress', 'note', 'payMethod', 'address_id'
				), array(
			array(
				'orderId', 'required|integer|greater_than[0]|exist[order.id]'
			), array(
				'orderAddress', 'required|integer|greater_than[0]'
			), array(
				'payMethod', 'in_list[1,2,3]'
			), array(
				'note', 'max_length[600]'
			), array(
				'address_id', 'integer|greater_than[0]'
			)
		));
		if ($this->form_validation->hasErrors()) {
			$data['msg'] = $this->form_validation->error;
			$this->renderJson(10005, $data);
		}
		$time = time();
		$this->load->model('api/Order_model', 'Order');
		$orderId = $this->form_validation->orderId;
		$order = $this->Order->getOrder($orderId);
		if($order['status'] > parent::PAY_STATUS_UNPAY) {
			$this->renderJson(10055);//已经支付
		} elseif($order['storeStatus'] != REST_Controller::STATUS_ACTIVE) {
			$this->renderJson(10053);//店家打烊
		} elseif($order['address_id'] != $this->form_validation->address_id) {
			$this->renderJson(10057);//不在配送范围内
		}
		$dilivery_address = $this->Order->addressValid($this->form_validation->orderAddress, $this->form_validation->address_id);
		if (empty($dilivery_address)) {
			$this->renderJson(10057);//不在配送范围内
		}
		$data = array(
			'pay_method' => $this->form_validation->payMethod,
			'note' => json_encode($this->form_validation->note),
			'updated_at' => $time
		);
		if ($data['pay_method'] == parent::PAY_METHOD_CASH) { //到付
			$data['pay_time'] = $time;
			$data['sign_for_code'] = rand(1000, 9999);
			$data['status'] = parent::PAY_STATUS_CASH;
		}
		$dataUpdate = array_merge($data, $dilivery_address);
		$result = $this->Order->pay($dataUpdate, $orderId);
		if ($result) {
			switch ($data['pay_method']) {
				case self::PAY_METHOD_CASH:
					//更新订单状态
					$short_desc = sprintf($this->lang->line('s10003'), $data['sign_for_code']);
					$this->Order->log($orderId, $data['status'], $short_desc, 3);
					//发送抢单消息
					$this->load->library('JPush');
					$this->load->model('api/Agent_model', 'Agent');
					$rows = $this->Agent->getAgentAll($order['address_id']);
					$audience = $this->toSimpleArray($rows, 'id');
					$this->jpush->push($audience, 'cfg_agent_notify_new', $order, array('data'=>$order['id']));
					$this->renderJson(11100);
					break;
				case self::PAY_METHOD_WECHAT:
					$order = $this->Order->orderDetails($this->form_validation->orderId, $order);
					$this->load->library('Wxpay');
					$result = $this->wxpay->createApiOrder($order);
					if ($result['return_code'] === "SUCCESS" && $result['result_code'] === "SUCCESS") {
						$this->Order->update(array('ext_order_num' => $result['prepay_id']), array('id' => $order['id']));
					} elseif (isset($result['err_code']) && strtoupper($result['err_code']) == 'OUT_TRADE_NO_USED') {
						$result['prepay_id'] = $order['ext_order_num'];
					} else {
						$this->renderJson(11300);
					}
					$tmp = array();
					$tmp['appid'] = $result['appid'];
					$tmp['partnerid'] = $result['mch_id'];
					$tmp['prepayid'] = $result['prepay_id'];
					$tmp['package'] = 'Sign=WXPay';
					$tmp['noncestr'] = $this->wxpay->getNonceStr();
					$tmp['timestamp'] = time();
					$tmp['sign'] = $this->wxpay->MakeSign($tmp);
					$tmp['_package'] = $tmp['package'];
					unset($tmp['package']);
					$this->renderJson(11100, array('data' => $tmp));
					break;
				case self::PAY_METHOD_ALIPY:
					$data = $this->Order->orderDetails($this->form_validation->orderId, $order);
					$tmp = array();
					$tmp['body'] = "【{$data['details'][0]['name']}】等{$data['request_num']}件商品";
					$tmp['details'] = '';
					foreach ($data['details'] as $v) {
						$tmp['details'] .= "【{$v['name']}】 x{$v['number']}\n";
					}
					$tmp['order_num'] = $data['order_num'];
					$tmp['netpay'] = $data['netpay'];
					$this->renderJson(11100, array('data' => $tmp));
					break;
				default:break;
			}
		}
		$this->renderJson(11200);
	}

	/**
	 * 我的订单接口
	 */
	public function myOrders() {
		$data = array();
		$this->load->model('api/Order_model', 'Order');
		$where = array('o.user_id' => $this->identity['uid']);
		$config = $this->page;
		$config['join'][] = array('comment c', 'o.id=c.order_id and o.user_id=c.user_id', 'left');
		$data['data'] = $this->Order->getOrders($where, $config, 'o.reminder,c.id comment,o.sign_for_code,');
		$this->renderJson(11100, $data);
	}

	/**
	 * 订单详情
	 */
	public function orderDetails() {
		$this->form_validation->validateData(array(
			'orderId'
				), array(
			array(
				'orderId', 'required|integer|greater_than[0]'
			)
		));
		if ($this->form_validation->hasErrors()) {
			$data['msg'] = $this->form_validation->error;
			$this->renderJson(10005, $data);
		}
		$this->load->model('api/Order_model', 'Order');
		$data['data'] = $this->Order->orderDetails($this->form_validation->orderId);
		$this->renderJson(11100, $data);
	}

	public function orderStatus() {
		$this->form_validation->validateData(array(
			'orderId'
				), array(
			array(
				'orderId', 'required|integer|greater_than[0]'
			)
		));
		if ($this->form_validation->hasErrors()) {
			$data['msg'] = $this->form_validation->error;
			$this->renderJson(10005, $data);
		}
		$this->load->model('api/Order_model', 'Order');
		$data = array();
		$data['data'] = $this->Order->orderStatus($this->form_validation->orderId);
		$this->renderJson(11100, $data);
	}

	public function reminder() {
		$this->form_validation->validateData(array(
			'orderId'
				), array(
			array(
				'orderId', 'required|integer|greater_than[0]'
			)
		));
		if ($this->form_validation->hasErrors()) {
			$data['msg'] = $this->form_validation->error;
			$this->renderJson(10005, $data);
		}
		$this->load->model('api/Order_model', 'Order');
		$data = array(
			'reminder' => REST_Controller::STATUS_ACTIVE,
			'updated_at' => time(),
		);
		$where = array(
			'id' => $this->form_validation->orderId,
			'reminder' => REST_Controller::STATUS_DELETE,
			'status >' => parent::PAY_STATUS_UNPAY,
			'status <' => parent::PAY_STATUS_SIGNED,
			'user_id' => $this->identity['uid'],
		);
		$result = $this->Order->update($data, $where);
		if ($result) {
			$order = $this->Order->get_row(array('id' => $where['id']));
			//记录日志
			$this->Order->log($order['id'], 19, $this->lang->line("s10019"), 1);
			//发送抢单消息
			$this->load->library('JPush');
			$this->load->model('api/Agent_model', 'Agent');
			$rows = $this->Agent->getAgentAll($order['address_id'], parent::ROLE_AGENT);
			$audience = $this->toSimpleArray($rows, 'id');
			if(!empty($order['agent_id'])) {
				$audience[] = $order['agent_id'];
				$audience = array_unique($audience);
			}
			$this->jpush->push($audience, 'cfg_agent_notify_reminder', $order, array('data'=>$order['id']));
			$this->renderJson(11100);
		}
		$this->renderJson(11200);
	}

	/**
	 * 关闭订单
	 */
	public function close() {
		$this->form_validation->validateData(array(
			'orderId'
				), array(
			array(
				'orderId', 'required|integer|greater_than[0]'
			)
		));
		if ($this->form_validation->hasErrors()) {
			$data['msg'] = $this->form_validation->error;
			$this->renderJson(10005, $data);
		}
		$this->load->model('api/Order_model', 'Order');
		$result = $this->Order->close($this->form_validation->orderId, $this->identity['uid']);
		if ($result) {
			$this->Order->log($this->form_validation->orderId, REST_Controller::PAY_STATUS_CLOSE, '', 1);
			$this->renderJson(11100);
		}
		$this->renderJson(11200);
	}

	public function finish() {
		$this->form_validation->validateData(array(
			'orderId'
				), array(
			array(
				'orderId', 'required|integer|greater_than[0]'
			)
		));
		if ($this->form_validation->hasErrors()) {
			$data['msg'] = $this->form_validation->error;
			$this->renderJson(10005, $data);
		}
		$this->load->model('api/Order_model', 'Order');
		$data = array(
			'status' => parent::PAY_STATUS_FINISH,
			'updated_at' => time(),
		);
		$where = array(
			'id' => $this->form_validation->orderId,
			'status' => parent::PAY_STATUS_SIGNED,
			'user_id' => $this->identity['uid'],
		);
		$result = $this->Order->update($data, $where);
		if ($result) {
			$this->Order->log($where['id'], $data['status'], '', 1);
			$this->renderJson(11100);
		}
		$this->renderJson(11200);
	}

}
